<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>反射(reflection) | haijd</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="c#学习笔记" />
  
  
  
  
  <meta name="description" content="反射(reflection)">
<meta name="keywords" content="c#学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="反射(reflection)">
<meta property="og:url" content="http://www.hais2.com/2015/06/18/c#-reflection/index.html">
<meta property="og:site_name" content="haijd">
<meta property="og:description" content="反射(reflection)">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://ww3.sinaimg.cn/mw690/c55a7aeejw1f1f9uf40o5j20qg07imxf.jpg">
<meta property="og:image" content="http://ww3.sinaimg.cn/mw690/c55a7aeejw1f1fdzu9662j20ry0gpjrc.jpg">
<meta property="og:updated_time" content="2017-08-02T15:22:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="反射(reflection)">
<meta name="twitter:description" content="反射(reflection)">
<meta name="twitter:image" content="http://ww3.sinaimg.cn/mw690/c55a7aeejw1f1f9uf40o5j20qg07imxf.jpg">
  
    <link rel="alternate" href="/atom.xml" title="haijd" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >
  <link rel="stylesheet" href="/css/hiero.css" >
  <link rel="stylesheet" href="/css/glyphs.css" >
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>

<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="haijd" rel="home"> haijd </a>
            
          </h1>

          
            <div class="site-description">Stay Hungry,Stay Foolish</div>
          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-c#-reflection" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      反射(reflection)
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2015/06/18/c#-reflection/" class="article-date">
	  <time datetime="2015-06-18T08:01:14.000Z" itemprop="datePublished">June 18, 2015</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="什么是反射"><a href="#什么是反射" class="headerlink" title="什么是反射"></a>什么是反射</h2><p>　　一个运行的程序查看本身或者其他程序的元数据的行为称为反射(reflection)。<br>　　元数据(metadata)：有关程序及其类型的数据称为元数据，它们保存在程序的程序集中。</p>
<p>　　<strong>反射功能引用自system.Reflection命名空间</strong>，要使用反射需要使用<code>System.Reflection</code>命名空间。<br>　　BCL(基类库)声明了一个叫做<code>Type</code>的抽象类，它被设计用来包含类型的特性，使用这个类的对象能让我们获取程序使用的类型的信息。<br><a id="more"></a></p>
<h3 id="Type类"><a href="#Type类" class="headerlink" title="Type类"></a>Type类</h3><p>　　● 对于程序中用到的每一个类型，CLR都会创建一个包含这个类型信息的Type类型的对象。<br>　　● 程序中用到的每一个类型都会关联到独立的Type类对象。<br>　　● 不管创建的类型有多少个实例，只有一个Type对象会关联到这些实例。</p>
<p>　　我们可以从Type对象中获取需要了解的有关类型的几乎所有的信息，Type类的几个主要成员：<br><img src="http://ww3.sinaimg.cn/mw690/c55a7aeejw1f1f9uf40o5j20qg07imxf.jpg" alt=""></p>
<h3 id="获取Type对象"><a href="#获取Type对象" class="headerlink" title="获取Type对象"></a>获取Type对象</h3><p>　　<strong>Type是一个抽象类，所以不能直接使用new关键字创建Type的实例</strong>。<br>　　有三种方法可以获取Type对象：<code>GetType()</code>、<code>Type.GetType()</code>、<code>typeof()</code></p>
<p>　　<strong>①：</strong><code>System.Object.GetType</code>方法是<code>object</code>类型所包含的一个方法，因为每一个类型都是继承自<code>object</code>的所以，我们可以在任何对象上使用<code>GetType</code>方法获得该类型的Type对象：<code>Type t = MyObject.GetType();</code><br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">static void Main(string[] args)</span><br><span class="line">&#123;</span><br><span class="line">   <span class="built_in"> Type </span>t = MyObject.GetType();</span><br><span class="line">    Console.WriteLine(<span class="string">"&#123;0&#125;"</span>,t.Name);</span><br><span class="line">    Console.WriteLine(<span class="string">"&#123;0&#125;"</span>,t.Namespace);</span><br><span class="line">    FieldInfo[] fi = t.GetFields();</span><br><span class="line">    <span class="keyword">foreach</span>(var f <span class="keyword">in</span> fi)</span><br><span class="line">    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"&#123;0&#125;"</span>,f.Name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　<strong>②：</strong>使用<code>typeof</code>运算符来获取Type对象，只需要提供类型名作为参数它就会返回Type对象的引用:<code>Type t = typeof(MyObject);</code><br><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">static void Main(string[] args)</span><br><span class="line">&#123;</span><br><span class="line">   <span class="built_in"> Type </span><span class="keyword">to</span> = typeof(MyObject);</span><br><span class="line">    Console.WriteLine(<span class="string">"&#123;0&#125;"</span>,<span class="keyword">to</span>.Name);</span><br><span class="line">    Console.WriteLine(<span class="string">"&#123;0&#125;"</span>,<span class="keyword">to</span>.Namespace);</span><br><span class="line">    FieldInfo[] fi = <span class="keyword">to</span>.GetFields();</span><br><span class="line">    <span class="keyword">foreach</span>(var f <span class="keyword">in</span> fi)</span><br><span class="line">    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"&#123;0&#125;"</span>,f.Name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　<strong>③：</strong><code>System.Type.GetType()</code>是一个静态方法，有三个参数的重载：<br>　　1. 类型的完全限定名(命名空间.类名)，字符串类型。<br>　　2. 当前类型找不到时是否抛出异常，bool类型。<br>　　3. 是否区分字符串的大小写，bool类型。<br><figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">//MyObject类的命名空间是“Reflection”，所以完全限定名就是：Reflection.MyObject</span><br><span class="line"><span class="keyword">Type</span> <span class="type">t </span>= <span class="keyword">Type</span>.GetType(<span class="string">"Reflection.MyObject"</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">Type</span> <span class="type">t1 </span>= <span class="keyword">Type</span>.GetType(<span class="string">"Reflection.MyObject"</span>,<span class="literal">true</span>,<span class="literal">true</span>);</span><br></pre></td></tr></table></figure></p>
<h3 id="利用反射调用已存在类库的方法"><a href="#利用反射调用已存在类库的方法" class="headerlink" title="利用反射调用已存在类库的方法"></a>利用反射调用已存在类库的方法</h3><p>基本步骤：<br>　　1. 加载程序集<br>　　2. 获得类型<br>　　3. 创建类型实例<br>　　4. 获得方法<br>　　5. 调用方法</p>
<p>　　首先我们创建一个类库，添加如下代码，然后生成dll文件：<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Conveyance</span></span><br><span class="line"> &#123;</span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">string</span> <span class="title">reuturn</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"这是交通工具"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Car</span> : <span class="title">Conveyance</span></span><br><span class="line"> &#123;</span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">string</span> <span class="title">reuturn</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"这是小汽车"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Ship</span> : <span class="title">Conveyance</span></span><br><span class="line"> &#123;</span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">string</span> <span class="title">reuturn</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"这是轮船"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Plan</span> : <span class="title">Conveyance</span></span><br><span class="line"> &#123;</span><br><span class="line">     <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">string</span> <span class="title">reuturn</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function">     </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="string">"这是飞机"</span>;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></p>
<p>　　然后在程序中调用这个dll文件中的类：<br><figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//加载程序集(dll文件)</span></span><br><span class="line">    Assembly a = Assembly.LoadFile(<span class="string">@"E:\cSharp练习\Conveyance\bin\Debug\Conveyance.dll"</span>);</span><br><span class="line">    <span class="comment">//获得类型</span></span><br><span class="line">    Type[] t = a.GetTypes();</span><br><span class="line">    <span class="keyword">foreach</span> (Type item <span class="keyword">in</span> t)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">string</span> str = item.ToString();</span><br><span class="line">        <span class="comment">//搜寻指定类型，使用系统激活器创建该类型的实例</span></span><br><span class="line">        <span class="keyword">object</span> objClass = a.CreateInstance(str);</span><br><span class="line">        MethodInfo mi = item.GetMethod(<span class="string">"reuturn"</span>);</span><br><span class="line">        Console.WriteLine(mi.Invoke(objClass,<span class="literal">null</span>));</span><br><span class="line">    &#125;</span><br><span class="line">    Console.ReadKey();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>运行结果：<img src="http://ww3.sinaimg.cn/mw690/c55a7aeejw1f1fdzu9662j20ry0gpjrc.jpg" alt=""></p>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/c/">c#</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/c-学习笔记/">c#学习笔记</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: '/css/images/wechatPay.png',
  alipayImage: '/css/images/alipay.jpg'
});
</script>
      

      
        
	<section id="comments" class="comment">
	  <div id="disqus_thread">
	  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
	  </div>
	</section>

	<script type="text/javascript">
	var disqus_shortname = 'haijdblog';
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/count.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	</script>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2015/07/13/Angular-module-simple-to-use/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          angular.module()的简单使用
        
      </div>
    </a>
  
  
    <a href="/2015/06/07/c#-array/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">数组(array)</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是反射"><span class="nav-number">1.</span> <span class="nav-text">什么是反射</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Type类"><span class="nav-number">1.1.</span> <span class="nav-text">Type类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取Type对象"><span class="nav-number">1.2.</span> <span class="nav-text">获取Type对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#利用反射调用已存在类库的方法"><span class="nav-number">1.3.</span> <span class="nav-text">利用反射调用已存在类库的方法</span></a></li></ol></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2018 haijd All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>








	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
